package websocket

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"strings"

	"log"

	"tuiwen-go/internal/api"
	"tuiwen-go/internal/db"
	"tuiwen-go/internal/utils"
)

var splitData struct {
	ProjectID string `json:"project_id"`
	Id        string `json:"id"`
	Split     string `json:"data"`
}

// 分词更新
func taskUpdateSplitHandler(c *Client, data json.RawMessage) {
	log.Printf("客户端 %s: 正在处理更新分词任务, 数据: %s", c.ID, string(data))
	if err := json.Unmarshal(data, &splitData); err != nil {
		log.Printf("客户端 %s: 解析分词任务数据失败: %v", c.ID, err)
		sendMessage(c, api.WxJSONResponse{Code: -1, Msg: "无效的数据格式"})
		return
	}

	if len(splitData.ProjectID) == 0 || len(splitData.Id) == 0 {
		sendMessage(c, api.WxJSONResponse{Code: -1, Msg: "ID不能为空"})
		return
	}
	// 使用生成的分词更新数据库
	sqlUpdate := "UPDATE text SET split = ?  WHERE project_id = ? AND id = ?"
	_, err := db.Exec(sqlUpdate, splitData.Split, splitData.ProjectID, splitData.Id)
	if err != nil {
		log.Printf("客户端 %s: 更新文本 ID %s 的分词失败: %d", c.ID, splitData.Id, err)
		// Continue processing other items, but log the error
	} else {
		sendMessage(c, api.WxJSONResponse{Code: 1, Msg: fmt.Sprintf("分词更新成功 (ID: %s)", splitData.Id)})
	}
}

// 分镜任务处理程序
func taskAutoSceneHandler(c *Client, data json.RawMessage) {
	log.Printf("客户端 %s: 正在处理分镜任务, 数据: %s", c.ID, string(data))
	if err := json.Unmarshal(data, &splitData); err != nil {
		log.Printf("客户端 %s: 解析分镜任务数据失败: %v", c.ID, err)
		sendMessage(c, api.WxJSONResponse{Code: -1, Msg: "无效的分镜任务数据格式"})
		return
	}

	if len(splitData.ProjectID) == 0 {
		sendMessage(c, api.WxJSONResponse{Code: -1, Msg: "项目ID不能为空"})
		return
	}

	// 获取需要生成分镜的文本条目
	sqlQuery := "SELECT id, content, split FROM text WHERE project_id = ? "
	args := []interface{}{splitData.ProjectID}
	if splitData.Id != "" {
		sqlQuery += " AND id = ?"
		args = append(args, splitData.Id)
	} else {
		sqlQuery += " AND (split IS NULL OR split = '')"
	}
	rows, err := db.Query(sqlQuery, args...)
	if err != nil {
		log.Printf("客户端 %s: 查询分镜任务文本失败: %v", c.ID, err)
		sendMessage(c, api.WxJSONResponse{Code: -1, Msg: "查询待生成分镜文本失败"})
		return
	}
	defer rows.Close()

	var textsToTranslate []struct {
		ID      int
		Content string
		Split   string
		Prompt  string
	}
	// rows转为json数组
	var texts []map[string]interface{}
	for rows.Next() {
		var id int
		var content string
		var splitJSON sql.NullString
		err := rows.Scan(&id, &content, &splitJSON)
		if err != nil {
			log.Printf("客户端 %s: 扫描分镜任务文本行失败: %v", c.ID, err)
			continue
		}
		texts = append(texts, map[string]interface{}{
			"id":      id,
			"content": content,
			"split":   splitJSON.String,
			"prompt":  "",
		})
	}

	if err = rows.Err(); err != nil {
		log.Printf("客户端 %s: 遍历分镜任务文本行失败: %v", c.ID, err)
		sendMessage(c, api.WxJSONResponse{Code: -1, Msg: "处理待生成分镜文本失败"})
		return
	}

	if len(texts) == 0 {
		sendMessage(c, api.WxJSONResponse{Code: 0, Msg: "分镜已全部生成"})
		return // No texts to translate
	}
	jsonData, err := json.Marshal(texts)
	if err != nil {
		fmt.Println("Error marshaling array to JSON: ", err)
		return
	}

	// 调用 GPT API 生成分镜
	generatedArrStr, err := utils.CallGPTAPI("split", string(jsonData))
	if err != nil {
		log.Printf("客户端 %s: 调用 GPT API 生成分镜失败: %v", c.ID, err)
		sendMessage(c, api.WxJSONResponse{Code: -1, Msg: "调用 GPT API 生成分镜失败"})
		return
	}
	fmt.Println("gpt返回:", generatedArrStr)
	generatedArrStr = strings.TrimPrefix(generatedArrStr, "```json")
	generatedArrStr = strings.TrimSuffix(generatedArrStr, "```")
	err = json.Unmarshal([]byte(generatedArrStr), &textsToTranslate)
	if err != nil {
		fmt.Println("gpt返回JSON解析错误:", err)
		return
	}
	// 根据数组中的id更新数据库中的split字段
	for _, item := range textsToTranslate {
		// 使用 GPT API 生成分镜
		if item.Split == "" {
			log.Printf("客户端 %s: 调用 GPT API 生成分镜失败 (ID: %d): %v", c.ID, item.ID, err)
			sendMessage(c, api.WxJSONResponse{Code: -1, Msg: fmt.Sprintf("分镜生成失败 (ID: %d): %v", item.ID, err)})
			continue // 继续处理下一个文本
		}

		// Update the database with the generated prompt
		// 使用生成的分镜更新数据库
		sqlUpdate := "UPDATE text SET split = ?,prompt = ? WHERE project_id = ? AND id = ?"
		_, err = db.Exec(sqlUpdate, item.Split, item.Prompt, splitData.ProjectID, item.ID)
		if err != nil {
			log.Printf("客户端 %s: 更新文本 ID %d 的分镜失败: %v", c.ID, item.ID, err)
			// Continue processing other items, but log the error
		} else {
			sendMessage(c, api.WxJSONResponse{Code: 1, Type: "splitItem", Msg: fmt.Sprintf("分镜生成成功 (ID: %d)", item.ID), Data: map[string]interface{}{
				"id":         item.ID,
				"split_data": item.Split,
				"prompt":     item.Prompt,
			}})
		}
	}
}
